﻿/* Header
 * File Name: ListCleanUpSettings.cs
 * Purpose: Code behind file for ListCleanUpSettings.aspx
 * Description: Used to configure cleanup settings for lists
 * Last updated date: Jul 13,2008
 * 
 * History
 * Date           User                Change              
 * Jul 13,2008    subvutt             Created             
 */
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.ApplicationPages;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Administration;
using System.Xml.Linq;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Codeplex.SPCleanup.SPUtilities.Cleanup;


namespace Codeplex.SPCleanup.ApplicationPages
{
    public class ListCleanupSettingsPage : ListPageBase
    {              
        // variable declarations
        protected InputFormCheckBox ChkEnableCleanUp;
        protected InputFormCheckBox ChkBrowseSubfolders;
        protected InputFormCheckBox ChkDeleteSubfolders;
        protected InputFormTextBox  TxtTimeSpan;
        protected InputFormCheckBox ChkSendNotification;
        protected HtmlInputButton BtnCancel;

        protected Panel pnlDocLibOptions;

        /// <summary>
        /// Attach the client javascript functions for disabling/enabling controls. Bind the values for the controls 
        /// if it exists already in cleanup config
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            if (!Page.IsPostBack)
            {
                ShowCurrentCleanUpSettings();                
            }

            // show the subfolders option only for document libraries.
            SPDocumentLibrary listDocLibrary = this.List as SPDocumentLibrary;
            if (null != listDocLibrary)
            {
                pnlDocLibOptions.Visible = true;
            }

            // client side functions to control enable/disable for enable cleanup checkbox event.
            ChkEnableCleanUp.Attributes.Add("onclick", "EnableDisableControls(this.checked)");
            ChkBrowseSubfolders.Attributes.Add("onclick", "EnableDisableDeleteFolderOption(this.checked)");

            // redirect from client itself.
            BtnCancel.Attributes.Add("onclick", "window.location='" + this.List.DefaultViewUrl + "'");

            // when form controls are disabled on client side , values will not be posted back. So when enable cleanup is 
            // unchecked all controls are disabled and hence values will not be posted back so text box value will be blank
            // and all flags will be false. Setting the form.submitdisabledcontrols to true should solve this problem in asp.net 2.0
            // this property generates a script for onsubmit event to renable the controls during submit in clientside. but
            // for sp it is not happening. Hence writing my own version of the function to reenable the required controls
            // during onsubmit.
            ClientScript.RegisterOnSubmitStatement(this.GetType(), "EnableControlOnSubmitScript", "EnableControls()");            
        }

        /// <summary>
        /// Custom validator to validate the time span value. Decimal with a maximum of 6 digits , with one decimal place
        /// or -1.
        /// </summary>
        /// <param name="source">custom validator control</param>
        /// <param name="args">event arguments</param>
        protected void ListCleanUp_CustomValidator(object source, ServerValidateEventArgs args)
        {
            CustomValidator CustValValue = source as CustomValidator;
            if (null != CustValValue)
            {                 
                if (true == ChkEnableCleanUp.Checked)
                {                                
                    Regex timeSpanRegEx = new Regex(@"^((\-1)?|(\d{1,4})+(\.\d{0,1})?)$");
                    if (!timeSpanRegEx.IsMatch(TxtTimeSpan.Text))
                    {
                        CustValValue.ErrorMessage = "Enter a valid input for time span. Decimal with max of 6 digits including one decimal point or -1.";
                        args.IsValid = false;
                    }                 
                }

            }
        }

        /// <summary>
        /// Event handler for save button. If the page validation succeeds then it proceeds to save the cleanup information.
        /// </summary>
        /// <param name="sender">button control</param>
        /// <param name="e">event arguments</param>
        protected void BtnSave_Click(object sender, EventArgs e)
        {
            // if validation has passed
            if (Page.IsValid)
            {
                UpdateListCleanUpInfo();
                
                Response.Redirect(this.List.DefaultViewUrl, false);
                
            }
        }

        /// <summary>
        /// Binds the values to the controls during initial page load.
        /// </summary>
        private void ShowCurrentCleanUpSettings()
        {                                    
            SiteDefinition lstCleanUpInfo = ConfigManager.GetCleanupSettingsForList(this.List.ID.ToString());            
            //SiteDefinition lstCleanUpInfo = ConfigManager.GetCleanupSettingsForList();            

            // update the UI
            if (null != lstCleanUpInfo)
            {
                if (lstCleanUpInfo.Sites.Count > 0 && lstCleanUpInfo.Sites[0].Lists.Count > 0)
                {
                    SiteList cleanupInfo = lstCleanUpInfo.Sites[0].Lists[0];
                    ChkEnableCleanUp.Checked = cleanupInfo.Enabled;
                    /*if (-1 == cleanupInfo.CleanupInfo.TimeSpan)
                    {
                        TxtTimeSpan.Text = "";
                    }
                    else
                    {
                        TxtTimeSpan.Text = cleanupInfo.CleanupInfo.TimeSpan.ToString();
                    }*/
                    TxtTimeSpan.Text = cleanupInfo.CleanupInfo.ItemTimeSpan.ToString();
                    ChkBrowseSubfolders.Checked = cleanupInfo.CleanupInfo.BrowseSubfolders;
                    ChkDeleteSubfolders.Checked = cleanupInfo.CleanupInfo.DeleteSubfolders;
                    ChkSendNotification.Checked = cleanupInfo.CleanupInfo.EmailOwner;
                }
            }
        }                      

        /// <summary>
        /// Called from save event handler to save the updated cleanup job settings for this list
        /// </summary>
        /// <returns></returns>
        private void UpdateListCleanUpInfo()
        {            
            //SiteDefinition lstCleanUpInfo = ConfigManager.GetCleanupSettingsForList(this.List.ID.ToString());
            SiteDefinition lstCleanUpInfo = ConfigManager.GetCleanupSettingsForList(); 
           
            SiteDefinition siteDef;
            Site site;
            SiteList list;            
          
            siteDef = new SiteDefinition();
            siteDef.ID = this.Site.ID;
            siteDef.SiteUri = new Uri(this.Site.Url);

            if (null != lstCleanUpInfo)
            {
                siteDef.Enabled = lstCleanUpInfo.Enabled;
            }
            else
            {
                siteDef.Enabled = true;
            }

            site = new Site();
            site.ID = this.Web.ID;

            if (null != lstCleanUpInfo && 0 < lstCleanUpInfo.Sites.Count)
            {
                site.Enabled = lstCleanUpInfo.Sites[0].Enabled;
            }
            else
            {
                site.Enabled = true;
            }

            list = new SiteList();
            list.ID = this.List.ID;
            list.Enabled = ChkEnableCleanUp.Checked;            
            if (!string.IsNullOrEmpty(TxtTimeSpan.Text.Trim()))
            {
                bool conversionResult;
                float value;
                conversionResult = float.TryParse(TxtTimeSpan.Text, out value);
                if (conversionResult)
                {
                    // default is -1 that is set
                    list.CleanupInfo.ItemTimeSpan = value;
                }
            }
            list.CleanupInfo.BrowseSubfolders = ChkBrowseSubfolders.Checked;
            list.CleanupInfo.DeleteSubfolders = ChkDeleteSubfolders.Checked;
            list.CleanupInfo.EmailOwner = ChkSendNotification.Checked;

            site.Lists.Add(list);
            siteDef.Sites.Add(site);

            ConfigManager.UpdateListCleanupSettings(siteDef);        
        }       
    }
}
